import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { CreateSortDto } from './dto/create-sort.dto';
import { UpdateSortDto } from './dto/update-sort.dto';
import { Sort } from './entities/sort.entity';

@Injectable()
export class SortService {
  constructor(
    @InjectRepository(Sort)
    private sortRepository: Repository<Sort>,
  ) {}

  async create(createSortDto: CreateSortDto): Promise<Sort> {
    // 使用 createSortDto 中的数据创建一个新的 Sort 实体
    const newSort = this.sortRepository.create(createSortDto);
    // 保存到数据库
    await this.sortRepository.save(newSort);
    return newSort;
  }

  async findAll() {
    // 获取所有分类
    return {
      data: {
        sortList: await this.sortRepository.find(),
      },
    };
  }

  async findOne(id: string) {
    // 根据 id 获取单个分类
    const sort = await this.sortRepository.findOne({
      where: { id: id },
    });
    // if (!sort) {
    //   throw new NotFoundException(`Sort with ID "${id}" not found`);
    // }
    return {
      data: sort ?? [],
    };
  }

  async update(id: string, updateSortDto: UpdateSortDto) {
    // 首先检查分类是否存在
    const sort = await this.sortRepository.findOne({
      where: { id },
    });
    if (!sort) {
      throw new NotFoundException(`Sort with ID "${id}" not found`);
    }
    // 更新分类字段
    this.sortRepository.merge(sort, updateSortDto);
    await this.sortRepository.save(sort);
    return {
      data: sort ?? [],
      msg: '更新分类信息成功',
    };
  }

  async remove(id: string) {
    // 首先检查分类是否存在
    const sort = await this.sortRepository.findOne({
      where: { id },
    });
    if (!sort) {
      throw new NotFoundException(`Sort with ID "${id}" not found`);
    }
    sort.is_deleted = true;
    // 根据 id 删除分类
    await this.sortRepository.save(sort);
    return {
      msg: `删除分类${sort.sort_name}成功`,
    };
  }
}
